import json
import re

from wt.init_param.task_init import TaskInit
from wt.untils.common_until import CommonUntil
from wt.connector import workflow_func


class DataBaseAPI(TaskInit):
    def __init__(self, res_db_log):
        super().__init__()
        self.common_until = CommonUntil(res_db_log)
        self.wt = workflow_func.WorkFlowExec(self.login_url, self.headers)

    def get_datasource_table_info(self, plugin_name, datasource_name, database_name, filer_name):
        """
        通用数据库表查询, get_datasource_table_info(JDBC-Mysql, auto_database_mysql_jdbc, qa_source, qa_source)
        :param plugin_name: 源类型
        :param datasource_name: 数据源名称
        :param database_name: 库名称
        :return:
        """
        self.wt_database_table_param["datasourceName"] = datasource_name
        self.wt_database_table_param["databaseName"] = database_name
        self.wt_database_table_param["filterName"] = filer_name

        params = self.wt_database_table_param
        res = self.wt.send_request(self.wt_database_table_url, "get", params=params)
        res_json = res.json()

        self.common_until.get_res_is_success(res, "【获取数据库表】{} {} 查询 PASS, 获取表：{}".format(plugin_name,
                                                                                                    database_name,
                                                                                                    res_json))

        res_data = res_json["data"]
        return res_data

    def is_exist_aaa_table(self, res_data="", is_exist_table=""):
        """
        判断表是否存在库内
        :param res_data:
        :param is_exist_table:
        :return:
        """
        try:
            str_index = res_data.index(is_exist_table)
            print("{} 在".format(is_exist_table))
            return True
        except:
            print("ERROR, {} 不在".format(is_exist_table))
        return False

    def get_table_info(self, database_name, data_source_name):
        """
        dameng 数据表查询
        :param database_name:
        :param data_source_name:
        :param is_exist_table:
        :return:
        """
        self.wt_database_table_param["databaseName"] = database_name
        self.wt_database_table_param["datasourceName"] = data_source_name
        self.get_datasource_table_info("PASS dameng数据库查询：", database_name, self.wt_database_table_param)

    def get_datasource_info(self, plugin_name, search_val, col):
        """
        查询数据库信息，例：id，conf
        :param plugin_name:  "JDBC-Mysql"
        :param search_val:  "auto_test_mysql"
        :param col:  查询 id, 查询 datasource_config
        :return:
        """
        self.wt_database_list_param["pluginName"] = plugin_name
        self.wt_database_list_param["searchVal"] = search_val

        res = self.wt.send_request(self.wt_datasource_list_url, "get", params=self.wt_database_list_param)
        res_json = res.json()
        res_data_id = 0
        try:
            res_data_len = len(res_json["data"]["totalList"])
            if res_data_len != 0:
                if col == "id":
                    res_data_id = res_json["data"]["totalList"][0]["id"]
                    res = "【查询数据源】 {} 类型 {} PASS，称对应id是：{} {}".format(plugin_name, search_val, res_data_id,
                                                                                 "\r\n")
                    print(res)
                    return res_data_id
                elif col == "datasource_config":
                    res_data_source_config = res_json["data"]["totalList"][0]["datasourceConfig"]
                    res = "【查询数据源】 {} 类型 {} PASS，称对应config 是：{} {}".format(plugin_name, search_val,
                                                                                      res_data_source_config, "\r\n")
                    print(res)
                    return res_data_source_config
        except Exception as e:
            res = "【查询数据源】异常 {} {}".format(e, "\r\n")
            print(res)
            self.res_db_log.write(res.encode('utf-8'))
            return res
        return False

    def create_datasource(self, db_type, db_name, create_info):
        """

        :param db_type: mysql, oracle
        :param db_name: auto_database_mysql_jdbc, auto_database_oracle_jdbc
        :param create_info: {'datasourceName': 'auto_database_mysql_jdbc', 'pluginName': 'JDBC-Mysq..}
        :return:
        """
        res = self.wt.send_request(self.wt_datasource_create_url, "post", params=create_info)
        self.common_until.get_res_is_success(res, "【创建数据源】 {} {}".format(db_type, db_name))
        return res.json()

    def delete_datasource(self, db_name, datasource_id):
        """
        删除数据源
        :param datasource_id:
        :return:
        """
        try:
            self.wt_datasource_delete_url = self.common_until.update_task_id_in_url(self.wt_datasource_delete_url,
                                                                                    "datasource")
            self.wt_datasource_delete_url = self.common_until.update_task_id_in_url(self.wt_datasource_delete_url,
                                                                                    "datasource", datasource_id)
            res = self.wt.send_request(self.wt_datasource_delete_url, "delete")
            self.common_until.get_res_is_success(res, "【删除数据源】 {} {} ".format(db_name, datasource_id))
            return res.json()
        except Exception as e:
            return {"msg": str(e)}
        return False

    def connect_datasource(self, plugin_name, datasource_name):
        """
        测试数据库连通性, connect_datasource("JDBC-Mysql", "auto_test_mysql")
        :param plugin_name:
        :param datasource_name:
        :return:
        """
        datasource_id = self.get_datasource_info(plugin_name, datasource_name, 'id')
        datasource_config = self.get_datasource_info(plugin_name, datasource_name, 'datasource_config')
        params = {
            "id": datasource_id,
            "pluginName": plugin_name,
            "datasourceConfig": json.dumps(datasource_config)
        }
        res = self.wt.send_request(self.wt_datasource_check_url, "post", params=params)
        self.common_until.get_res_is_success(res, "【链接数据源】 {}".format(datasource_name))
        return res.json()


if __name__ == '__main__':
    m = DataBaseAPI("./")
    # m.batch_datasource_query()
    # m.get_table_info("DAMENG", "jdbc_dameng", "QA_SOURCE.AAA1")
    # m.get_datasource_info("JDBC-DAMENG", "jdbc_dameng", "id")
    # m.create_datasource("JDBC-Mysql", "auto_test_mysql")
    # m.create_datasource("JDBC-Oracle", "auto_database_oracle_jdbc")
    # m.create_datasource("JDBC-Postgres", "auto_database_psql_jdbc")
    # m.create_datasource("JDBC-SQLServer", "auto_database_sqls_jdbc")
    # m.create_datasource("JDBC-TiDB", "auto_database_tidb_jdbc")
    # m.create_datasource("JDBC-DAMENG", "auto_database_dameng_jdbc")
    # m.create_datasource("JDBC-DB2", "auto_database_db2_jdbc")
    # m.create_datasource("JDBC-Informix", "auto_database_informix_jdbc")
    # m.create_datasource("JDBC-OpenGauss", "auto_database_opengauss_jdbc")
    # m.create_datasource("JDBC-Sqlite", "auto_database_sqlite_jdbc")
    # m.create_datasource("Informix-CDC", "auto_database_informix_cdc")
    # m.create_datasource("MongoDB-CDC", "auto_database_mongodb_cdc")
    # m.create_datasource("Postgres-CDC", "auto_database_psql_cdc")
    # m.create_datasource("Postgres-CDC", "auto_database_highgo_cdc")
    # m.create_datasource("Oracle-CDC", "auto_database_oracle_cdc")
    # m.create_datasource("Dameng-CDC", "auto_database_dameng_cdc")
    # m.create_datasource("ElasticSearch", "auto_database_es")
    # m.create_datasource("LocalFile", "auto_database_localfile")
    # m.create_datasource("FtpFile", "auto_database_ftpfile")
    # m.create_datasource("SftpFile", "auto_database_sftpfile")
    # m.create_datasource("OssFile", "auto_database_ossfile")
    # m.create_datasource("Doris", "auto_database_doris_v2")
    #
    # m.connect_datasource("Doris", "auto_database_doris_v2")
    # id = m.get_datasource_info("Postgres-CDC", "auto_database_highgo_cdc","id")
    # if id != 0:
    #     m.delete_datasource(id)
    # m.get_datasource_table_info("DAMENG", "jdbc_dameng")
    # m.get_datasource_table_info("JDBC-Mysql","auto_database_mysql_jdbc", "qa_source", "qa_source" )
    m.create_datasource()
